import axios, { type AxiosRequestConfig } from "axios";
import { getToken } from "./cookieMgr";
import cf from "@/cf";
const ins = axios.create({
  baseURL: cf.API_URL,
  timeout: 20000,
  headers: { "Content-Type": "application/json" },
});
const instance = {
  get: async (
    path: string,
    params?: any,
    config: AxiosRequestConfig = {}
  ): Promise<ResponseApiDto> => {
    var paramsStr = new URLSearchParams(params);
    var response = await ins.get(
      path + (paramsStr ? "?" + paramsStr : ""),
      config
    );
    return response as unknown as ResponseApiDto;
  },
  post: async (
    path: string,
    data: any,
    config: AxiosRequestConfig = {}
  ): Promise<ResponseApiDto> => {
    var response = await ins.post(path, data, config);
    return response as unknown as ResponseApiDto;
  },
};

ins.interceptors.request.use(
  function (config) {
    config.headers.Authorization = `Bearer ${getToken()}`;
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
function getPromiseApiResponse(
  code: ResponseCode,
  message: string,
  data: any
): Promise<ResponseApiDto> {
  return new Promise((resolve) => {
    var d = {
      code: code,
      message: message,
      data: data,
    } as ResponseApiDto;
    resolve(d);
  });
}

// 添加响应拦截器
ins.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response.data;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    // 将错误转化为 Promise 避免报错
    if (error.response) {
      switch (error.response.status) {
        case 401:
          return getPromiseApiResponse(-1, "未登录或登录已过期", {
            res: error,
          });
        case 403:
          return getPromiseApiResponse(-1, "无权限访问", { res: error });
        case 404:
          return getPromiseApiResponse(-1, "资源不存在", { res: error });
        case 500:
          return getPromiseApiResponse(-1, "服务器错误", { res: error });
        default:
          return getPromiseApiResponse(-1, "未知错误", { res: error });
      }
    } else {
      return getPromiseApiResponse(-1, "服务器无响应或响应格式错误", {
        res: error,
      });
    }
  }
);

export default instance;
